<template>
  <div class="index">
    <div class="return" @click="toReturn()">
      <van-icon name="arrow-left" size="20" color="grey" />
    </div>
    <!-- 轮播图 -->
    <div class="index-top">
      <img :src="banner" />
      <div class="record" @click="toMine()">预约记录</div>
    </div>
    <div v-if="active == 1">
      <!-- 表单 -->
      <div class="form-div">
        <van-cell-group inset>
          <van-field
            input-align="right"
            v-model="name"
            required
            label="姓名"
            placeholder="请输入真实姓名"
          />
          <van-field
            input-align="right"
            v-model="phone"
            type="tel"
            required
            label="手机号"
            placeholder="请输入手机号"
          />
          <van-field
            input-align="right"
            v-model="date"
            required
            label="预约日期"
            placeholder="请选择"
            readonly
            is-link
            @click="toShow"
          />
          <van-field
            input-align="right"
            @click="toShow2"
            v-model="time"
            is-link
            required
            readonly
            label="预约时间段"
            placeholder="请选择"
          />
        </van-cell-group>
        <!-- <div class="tips"><span>*</span>入馆后不限在馆阅读时长</div> -->
      </div>
      <!-- 按钮 -->
      <div class="btn" @click="toSubmit">确定预约</div>
    </div>
    <div v-if="active == 2">
      <!-- 读者须知 -->
      <div class="notes">
        <div class="titleN">{{ nameCul }}简介</div>
        <div class="titleN titleN2">{{ description }}·INTRO</div>
        <div class="con" v-html="content"></div>
      </div>
      <!-- 地图 -->
      <div class="titleN">{{ nameCul }}位置</div>
      <div class="titleN titleN2">{{ description }}·LOCATION</div>
      <div class="map">
        <div class="baidumap" id="allmap"></div>
      </div>
    </div>
    <!-- 日期选择 -->
    <van-popup v-model="show" position="bottom">
      <!-- <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirm"
        @cancel="cancel"
        :formatter="formatter"
      /> -->
      <van-picker
        title="时间段选择"
        :columns="columns1"
        @confirm="onConfirm1"
        @cancel="show = false"
        show-toolbar
      />
    </van-popup>
    <!-- 时间段选择 -->
    <van-popup v-model="show2" position="bottom">
      <van-picker
        title="时间段选择"
        :columns="columns"
        @confirm="onConfirm"
        @cancel="show2 = false"
        show-toolbar
      />
    </van-popup>
    <!-- 日历 -->
    <van-calendar
      :formatter="formatter"
      color="#1989fa"
      v-model="show3"
      :min-date="minDate"
      :max-date="maxDate"
      :default-date="defaultDate"
      @confirm="onConfirmDate"
    />
    <!-- 导航栏 -->
    <div class="nav-item" style="z-index: 9">
      <div class="navs" :class="active == 2 ? 'navs-a' : ''" @click="toAct(2)">
        <img src="@/assets/icon1-a.png" v-if="active == 2" />
        <img src="@/assets/icon1.png" v-else />
        <div>{{ globalData }}</div>
      </div>
      <div class="navs" :class="active == 1 ? 'navs-a' : ''" @click="toAct(1)">
        <img src="@/assets/icon2-a.png" v-if="active == 1" />
        <img src="@/assets/icon2.png" v-else />
        <div>我要预约</div>
      </div>
      <div class="navs" @click="toMine">
        <img src="@/assets/icon3.png" />
        <div>预约记录</div>
      </div>
    </div>
  </div>
</template>
<script>
var infoWindow;
import {
  Toast,
  Swipe,
  SwipeItem,
  NoticeBar,
  Field,
  CellGroup,
  DatetimePicker,
  Popup,
  Picker,
  Dialog,
  Icon,
  Calendar,
} from "vant";
import getFormatDates from "@/until/getFormatDates.js";
import {
  positionDetail,
  positionList,
  memberInfo,
  culturalDetail,
  wechatLogin,
  appointmentAdd,
  appointmentOptions,
  getWxConfig,
  appointmentDateOp,
} from "@/api/apiData";
import { mapState, mapMutations } from "vuex";
let disabledDays = [];
export default {
  components: {
    [Toast.name]: Toast,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [NoticeBar.name]: NoticeBar,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      show3: false,
      active: 1,
      name: "",
      phone: "",
      date: "",
      banner: [],
      notice: "",
      time: "",
      content: "", //读者须知
      show: false,
      show2: false,
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2010, 0, 31),
      currentDate: new Date(),
      defaultDate: new Date(),
      ticket: "",
      info: "",
      time_index: "",
      date_id: "",
      formatter: (day) => {
        const year = day.date.getFullYear();
        const month = day.date.getMonth() + 1;
        const date = day.date.getDate();
        const dateString = `${year}-${month >= 10 ? month : "0" + month}-${
          date >= 10 ? date : "0" + date
        }`;
        if (disabledDays.includes(dateString)) {
          day.type = "disabled";
        }
        return day;
      },
      // columns:['9点-12点(剩余名额 0人)','9点-12点(剩余名额 0人)','9点-12点(剩余名额 0人)']
      columns: [],
      columns1: [],
      appid: "",
      cultural_center_id: "", //场馆id
      apply_date: "",
      apply_time: "",
      apply_date_A: [],
      latitude: "",
      longitude: "",
      mapName: "",
      address: "",
      map: null,
      nameCul: "",
      description: "",
    };
  },
  mounted() {
    // let id = this.getUrlCode("code");
    let id = this.$route.query.id;
    let active = this.$route.query.active;
    if (id) {
      this.cultural_center_id = id;
    }
    if (active) {
      this.active = active;
      if (active == 2) {
        setTimeout(() => {
          this.initMap();
        }, 500);
      }
    }
    let name = localStorage.getItem("name");
    let phone = localStorage.getItem("phone");
    if (name) {
      this.name = name;
    }
    if (phone) {
      this.phone = phone;
    }
    this.getInfo();
    this.getCulDel();
  },
  computed: {
    ...mapState(["globalData"]), // 映射this.globalData到store中的globalData
    ...mapMutations(["setGlobalData"]), // 映射this.globalData到store中的globalData
  },
  methods: {
    getCulDel() {
      culturalDetail({ cultural_center_id: this.cultural_center_id }).then(
        (res) => {
          if (res.code == 1) {
            this.notice = this.getText(res.data.description);
            this.banner = res.data.cover;
            this.nameCul = res.data.name;
            this.content = res.data.content;
            this.latitude = res.data.latitude;
            this.longitude = res.data.longitude;
            this.mapName = res.data.name;
            this.address = res.data.address;
            this.description = res.data.description;
            window.document.title = res.data.name + "预约";
            this.$store.commit("setGlobalData", res.data.name);
            appointmentOptions({
              cultural_center_id: this.cultural_center_id,
            }).then((res) => {
              let obj = res.data;
              const result = Object.keys(obj).map((el) => {
                return {
                  text: el,
                  children: obj[el],
                };
              });
              result.forEach((item) => {
                item.children = Object.keys(item.children).map((el) => {
                  return {
                    value: el,
                    people: item.children[el].last_people,
                    label:
                      item.children[el].start_time +
                      "-" +
                      item.children[el].end_time,
                    text:
                      item.children[el].start_time +
                      "-" +
                      item.children[el].end_time +
                      "(剩余" +
                      item.children[el].last_people +
                      "人)",
                  };
                });
              });
              if (result.length > 0) {
                let start = result[0].text;
                let end = result[result.length - 1].text;
                let dateS = start.split("-");
                let dateE = end.split("-");
                this.minDate = new Date(
                  dateS[0],
                  Number(dateS[1]) - 1,
                  dateS[2]
                );
                this.maxDate = new Date(
                  dateE[0],
                  Number(dateE[1]) - 1,
                  dateE[2]
                );
                this.defaultDate = this.minDate;
                this.columns1 = result;
              }
            });
            appointmentDateOp({
              cultural_center_id: this.cultural_center_id,
              month: this.getMonth(),
            }).then((res) => {
              if (res.code == 1) {
                let obj = res.data;
                const arr = Object.keys(obj).map((key) => key);
                disabledDays = arr;
                appointmentDateOp({
                  cultural_center_id: this.cultural_center_id,
                  month: this.getMonth2(),
                }).then((res) => {
                  if (res.code == 1) {
                    let obj = res.data;
                    const arr = Object.keys(obj).map((key) => key);
                    disabledDays = disabledDays.concat(arr);
                    // console.log(disabledDays)
                  }
                });
              }
            });
          }
        }
      );
    },
    getMonth() {
      const now = new Date(); // 创建 Date 对象，包含当前日期和时间

      // 获取年、月、日（注意月份从 0 开始，需要 +1）
      const year = now.getFullYear(); // 2025（四位年份）
      const month = now.getMonth() + 1; // 6（实际是 6 月，但 getMonth() 返回 5）
      const day = now.getDate(); // 9（当月的第几天）

      // 格式化为 YYYY-MM-DD
      const formattedDate = `${year}-${month.toString().padStart(2, "0")}`;
      return formattedDate;
    },
    getMonth2() {
      const now = new Date(); // 创建 Date 对象，包含当前日期和时间

      // 获取年、月、日（注意月份从 0 开始，需要 +1）
      const year = now.getFullYear(); // 2025（四位年份）
      const month = now.getMonth() + 2; // 6（实际是 6 月，但 getMonth() 返回 5）
      const day = now.getDate(); // 9（当月的第几天）

      // 格式化为 YYYY-MM-DD
      const formattedDate = `${year}-${month.toString().padStart(2, "0")}`;
      return formattedDate;
    },
    onConfirmDate(date) {
      let dateN = getFormatDates(date);
      this.show3 = false;
      let arr = this.columns1;
      let obj = [];
      console.log(arr);
      arr.forEach((item) => {
        if (item.text.replace(/\s/g, "") == dateN.replace(/\s/g, "")) {
          obj = item.children;
        }
      });
      console.log(obj);
      if (obj.length == 0) {
        Toast.fail("该日期暂无名额，请重新选择");
      } else {
        this.date = dateN;
        this.columns = obj;
        this.apply_time = "";
        this.time = "";
      }
    },
    toAct(a) {
      this.active = a;
      if (a == 2) {
        setTimeout(() => {
          this.initMap();
        }, 500);
      } else {
        if (this.map != null) {
          this.map.destroy(); // 销毁地图实例
          this.map = null; // 清除引用
        }
      }
    },
    toReturn() {
      window.history.go(-1);
    },
    // 获取用户信息
    getInfo() {
      memberInfo().then((res) => {
        if (res.code == 10000 || res.code == 20003) {
          this.getConfig();
        } else if (res.code == 1) {
          this.info = res.data;
        } else {
          Toast(res.msg);
        }
      });
    },
    getConfig() {
      // this.checkWeChatCode();
      getWxConfig().then((res) => {
        if (res.code == 1) {
          this.appid = res.data.appId;
          this.checkWeChatCode();
        } else {
        }
      });
    },
    //检查浏览器地址栏中微信接口返回的code
    checkWeChatCode() {
      let code = this.getUrlCode("code");
      if (code) {
        this.getOpenidAndUserinfo(code);
      } else {
        this.wxLogin();
        // this.getInfo()
      }
    },
    getOpenidAndUserinfo(code) {
      wechatLogin({ code: code }).then((res) => {
        if (res.code == 1) {
          localStorage.setItem("token", res.data.token);
          this.getInfo();
        } else {
          Toast.fail(res.msg);
          let id = this.getUrlCode("id");
          window.location.replace(
            "https://gxtravel.ncscloudmedia.com/gxyy/#/index?id=" + id
          );
        }
      });
    },
    wxLogin() {
      let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
      // let appid = "wx0d3c07901732c258";
      let appid = this.appid;
      //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
      let href =
        "https://ncymkj.doudou00.com/get-weixin-code.html?appid=" +
        appid +
        "&response_type=code&state=123456&scope=snsapi_userinfo&redirect_uri=" +
        local +
        "#wechat_redirect";
      console.log(href);
      window.location.href = href;
    },
    getUrlCode(name) {
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
    getSwiper() {
      positionList({ position_id: 1 }).then((res) => {
        if (res.code == 1) {
          this.banner = res.data;
          console.log(res.data);
        } else {
          Toast.fail(res.msg);
        }
      });
      positionDetail({ position_id: 2 }).then((res) => {
        if (res.code == 1) {
          this.notice = this.getText(res.data.content);
        } else {
          Toast.fail(res.msg);
        }
      });
      positionDetail({ position_id: 3 }).then((res) => {
        if (res.code == 1) {
          this.content = res.data.content;
        } else {
          Toast.fail(res.msg);
        }
      });
    },
    getText(str) {
      return str.replace(/<[^<>]+>/g, "").replace(/&nbsp;/gi, "");
    },
    // 确定预约
    toSubmit() {
      let obj = {
        cultural_center_id: this.cultural_center_id,
        realname: this.name,
        phone: this.phone,
        apply_date: this.date,
        apply_time: this.apply_time,
      };
      var reg_tel =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; //11位手机号码正则
      if (obj.realname == "") {
        Toast.fail("请输入姓名");
      } else if (!reg_tel.test(obj.phone)) {
        Toast.fail("请输入正确的手机号");
      } else if (obj.apply_date == "") {
        Toast.fail("请选择预约日期");
      } else if (obj.apply_time == "") {
        Toast.fail("请选择预约时间段");
      } else {
        console.log(obj);
        Dialog.confirm({
          title: "提示",
          message: "确定要预约吗？",
        })
          .then(() => {
            // on confirm
            appointmentAdd(obj).then((res) => {
              if (res.code == 1) {
                Toast.success(res.msg);
                let id = this.$route.query.id;
                localStorage.setItem("name", obj.realname);
                localStorage.setItem("phone", obj.phone);
                this.$router.replace({
                  path: "/bookList",
                  query: {
                    id: id,
                  },
                });
              } else {
                Toast.fail(res.msg);
              }
            });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    toMine() {
      let id = this.$route.query.id;
      this.$router.replace({
        path: "/bookList",
        query: {
          id: id,
        },
      });
    },
    initMap() {
      let latitude = this.latitude;
      let longitude = this.longitude;
      let name = this.mapName;
      let address = this.address;
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(latitude, longitude);
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      var map = new window.TMap.Map(document.getElementById("allmap"), {
        center: center, // 设置地图中心点坐标
        zoom: 18, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45, // 设置地图旋转角度
      });
      this.map = map;
      var marker = new TMap.MultiMarker({
        map: map,
        styles: {
          // 点标记样式
          marker: new TMap.MarkerStyle({
            width: 10, // 样式宽
            height: 15, // 样式高
            anchor: { x: 10, y: 30 }, // 描点位置
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
          }),
        },
        geometries: [
          // 点标记数据数组
          {
            // 标记位置(纬度，经度，高度)
            position: center,
            id: "marker",
          },
        ],
      });
      marker.on("click", function (evt) {
        let infoWindow = new TMap.InfoWindow({
          map: map,
          // enableCustom: true,
          position: evt.geometry.position,
          offset: { y: -5, x: -5 },
          content:
            '<div class="info_card"><div class="title"><span class="title_name">' +
            name +
            '</span><div class="close_img" onclick="closeInfoWindow()"><span class="min top_img"></span><span class="min right_img"></span><span class="min bottom_img"></span><span class="min left_img"></span></div></div><div align="left" class="content">' +
            address +
            '</div><a style="text-align:right;display:block" href="//uri.amap.com/search?keyword=' +
            address +
            '">导航</a><span class="cancle bot"></span><span class="cancle top"></span></div>',
        });
        infoWindow.open();
        // 设置中心点
        map.setCenter(new TMap.LatLng(latitude, longitude));
      });
    },
    openInfoWindow() {
      infoWindow.open();
    },
    toUrl() {
      window.location.href =
        "//uri.amap.com/search?keyword=江西省南昌市青山湖区湖滨东路海螺书屋";
      // location.href = `https://uri.amap.com/navigation
      //     ?from=${s.slng},${s.slat},${s.slocation}
      //     &to=${e.lng},${e.lat},${e.location}
      //     &mode=car&callnative=1&coordinate=wgs84&src=mypage`;
    },
    toShow() {
      this.show3 = true;
    },
    confirm(v) {
      console.log(v);
      console.log(getFormatDates(v));
      this.date = getFormatDates(v);
      this.show = false;
    },
    cancel() {
      this.show = false;
    },
    onConfirm(value, index) {
      // console.log("onConfirm");
      // console.log(value);
      // console.log(index);
      // this.time_index = value.key;
      this.show2 = false;
      if (value.people == 0) {
        Toast.fail("该时间段暂无名额，请重新选择");
      } else {
        this.apply_time = value.value;
        this.time = value.label;
      }
    },
    onConfirm1(value, index) {
      // console.log(value);
      // console.log(index);
      let i = index[1];
      this.show = false;
      this.date =
        value[0] + " " + this.columns1[index[0]].children[index[1]].label;
      this.apply_date = value[0];
      this.apply_time = this.columns1[index[0]].children[index[1]].value;
      console.log(this.apply_time);
    },
    toShow2() {
      if (this.date == "") {
        Toast.fail("请选择预约日期");
      } else {
        this.show2 = true;
      }
    },
  },
};
</script>
<style scoped>
.record{
  position: absolute;
  top: 30px;
  right: 0;
  background: #12d5b4;
  color: white;
  font-size: 14px;
  padding: 5px 6px 5px 10px;
  border-radius: 10px 0 0 10px;
}
.return {
  position: absolute;
  left: 0;
  top: 10px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 0 10px 10px 0;
  padding: 5px 10px 5px 5px;
  z-index: 2;
  font-size: grey;
}
.index-top {
  position: relative;
}
.index-top img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.index {
  padding-bottom: 50px;
}
.my-swipe .van-swipe-item {
  color: #fff;
  width: 100%;
  height: 100%;
}
.van-swipe-item img {
  width: 100%;
  height: 230px;
  display: block;
  object-fit: cover;
}
.notice-bar {
  position: absolute;
  width: 100%;
  padding: 0;
  bottom: 0;
}
.tips {
  text-align: right;
  padding: 5px;
  color: #333;
}
.tips span {
  color: #ee0a24;
}
.btn {
  width: 90%;
  background: #12d5b4;
  margin: 30px auto;
  /* border-radius: 30px; */
  text-align: center;
  line-height: 2.5;
  color: #fff;
  font-size: 15px;
}
.notes {
  /* background: #efefef; */
  width: 90%;
  margin: 10px auto;
  font-size: 14px;
  /* color: #333; */
  line-height: 23px;
}
.notes .con {
  border: solid 2px #d4c0ab;
  padding: 10px 10px;
  border-radius: 5px;
  margin-top: 10px;
  margin-bottom: 20px;
}
.title {
  font-size: 18px;
  text-align: center;
  font-weight: bold;
  margin-bottom: 20px;
}
.titleN {
  text-align: center;
}
.titleN2 {
  line-height: 0.8;
}
.baidumap {
  height: 250px;
  padding: 10px;
}
.map {
  width: 90%;
  margin: 15px auto;
  border-radius: 5px;
  border: solid 2px #d4c0ab;
  position: relative;
  z-index: 2;
}
</style>